<script setup lang="ts">
import { ref, reactive, h, computed, onMounted } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { TableColumn, PaginationConfig } from "@/components/DynamicTable/types";
import { ElMessage, ElTag, ElCard } from "element-plus";
import { getQaLogs, getQaLogsStats } from "./servers";
import DynamicStatistics from "@/components/DynamicStatistics/index.vue";
import type { StatisticsItem } from "@/components/DynamicStatistics/index.vue";
import DynamicForm from "@/components/DynamicForm";

const loading = ref(false);
const logList = ref<any[]>([]);
const statistics = ref<any>(null);
const statisticsItems = ref<StatisticsItem[]>([]);

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

// 筛选表单数据
const filterForm = reactive({
  date_range: "today",
  start_date: "",
  end_date: "",
  log_type: "all",
  used_ai: null as boolean | null,
  min_response_time: null as number | null,
  user_id: null as string | null,
});

// 筛选表单配置
const formConfig = [
  {
    key: "date_range",
    name: "时间范围",
    type: "select" as const,
    defaultValue: "today",
    placeholder: "请选择时间范围",
    params: {
      clearable: false,
    },
    options: [
      { label: "今天", value: "today" },
      { label: "昨天", value: "yesterday" },
      { label: "最近7天", value: "7d" },
      { label: "最近30天", value: "30d" },
      { label: "自定义", value: "custom" },
    ],
    col: {
      span: 6,
    },
  },
  {
    key: "start_date",
    name: "开始日期",
    type: "date" as const,
    defaultValue: "",
    placeholder: "请选择开始日期",
    params: {
      type: "date",
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD",
      clearable: true,
    },
    col: {
      span: 6,
    },
    show: (formData: any) => formData.date_range === "custom",
  },
  {
    key: "end_date",
    name: "结束日期",
    type: "date" as const,
    defaultValue: "",
    placeholder: "请选择结束日期",
    params: {
      type: "date",
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD",
      clearable: true,
    },
    col: {
      span: 6,
    },
    show: (formData: any) => formData.date_range === "custom",
  },
  {
    key: "log_type",
    name: "类型",
    type: "select" as const,
    defaultValue: "all",
    placeholder: "请选择类型",
    params: {
      clearable: false,
    },
    options: [
      { label: "全部", value: "all" },
      { label: "QA", value: "qa" },
      { label: "图谱", value: "graph" },
    ],
    col: {
      span: 6,
    },
  },
  {
    key: "used_ai",
    name: "AI回答",
    type: "select" as const,
    defaultValue: null,
    placeholder: "全部",
    params: {
      clearable: true,
    },
    options: [
      { label: "全部", value: null },
      { label: "是", value: true },
      { label: "否", value: false },
    ],
    col: {
      span: 6,
    },
  },
];

// 获取日志类型标签（根据answer字段判断）
const getLogTypeTag = (
  log: any
): {
  text: string;
  type: "success" | "warning" | "info" | "danger" | "";
} => {
  // 如果answer是JSON字符串且包含answer_type，根据类型判断
  if (log.answer) {
    try {
      const answerObj = JSON.parse(log.answer);
      if (
        answerObj.answer_type === "graph" ||
        answerObj.answer_type === "mixed"
      ) {
        return { text: "图谱", type: "success" as const };
      }
    } catch (e) {
      // 不是JSON，忽略
    }
  }
  // 默认都是QA类型
  return { text: "QA", type: "info" as const };
};

// 获取状态标签
const getStatusTag = (
  log: any
): { text: string; type: "success" | "warning" | "info" | "danger" | "" } => {
  if (log.matched_rule_id) {
    return { text: "命中规则", type: "success" };
  }
  if (log.used_ai) {
    return { text: "AI回答", type: "warning" };
  }
  return { text: "规则匹配", type: "info" };
};

const columns = ref<TableColumn[]>([
  {
    label: "时间",
    prop: "created_time",
    width: 180,
    show: true,
  },
  {
    label: "用户",
    prop: "user_id",
    width: 120,
    show: true,
  },
  {
    label: "问题/查询",
    prop: "question",
    minWidth: 250,
    show: true,
  },
  {
    label: "类型",
    prop: "log_type",
    width: 100,
    show: true,
    render: (row) => {
      const typeInfo = getLogTypeTag(row);
      return h(
        ElTag,
        { type: typeInfo.type, size: "small" },
        () => typeInfo.text
      );
    },
  },
  {
    label: "耗时",
    prop: "response_time_ms",
    width: 100,
    show: true,
    render: (row) => {
      const time = row.response_time_ms || 0;
      return h("span", {}, `${time}ms`);
    },
  },
  {
    label: "状态",
    prop: "status",
    width: 120,
    show: true,
    render: (row) => {
      const statusInfo = getStatusTag(row);
      return h(
        ElTag,
        { type: statusInfo.type, size: "small" },
        () => statusInfo.text
      );
    },
  },
  {
    label: "置信度",
    prop: "confidence",
    width: 100,
    show: true,
    render: (row) => {
      const confidence = row.confidence;
      if (confidence !== null && confidence !== undefined) {
        return h("span", {}, `${(confidence * 100).toFixed(0)}%`);
      }
      return h("span", {}, "-");
    },
  },
]);

// 获取日志列表
const fetchLogList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      per_page: pagination.pageSize,
      date_range: filterForm.date_range,
      log_type: filterForm.log_type,
    };

    if (filterForm.date_range === "custom") {
      if (filterForm.start_date) {
        params.start_date = filterForm.start_date;
      }
      if (filterForm.end_date) {
        params.end_date = filterForm.end_date;
      }
    }

    if (filterForm.used_ai !== null) {
      params.used_ai = filterForm.used_ai;
    }

    if (filterForm.min_response_time !== null) {
      params.min_response_time = filterForm.min_response_time;
    }

    if (filterForm.user_id) {
      params.user_id = filterForm.user_id;
    }

    const result = await getQaLogs(params);

    if (result.code === 2000 && result.data) {
      logList.value = result.data.logs || [];
      pagination.total = result.data.total || 0;
      // 更新当前页码（如果接口返回了page）
      if (result.data.page) {
        pagination.currentPage = result.data.page;
      }
    } else {
      ElMessage.error(result.message || "获取日志列表失败");
      logList.value = [];
      pagination.total = 0;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取日志列表失败");
    logList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const params: any = {
      date_range: filterForm.date_range,
    };

    if (filterForm.date_range === "custom") {
      if (filterForm.start_date) {
        params.start_date = filterForm.start_date;
      }
      if (filterForm.end_date) {
        params.end_date = filterForm.end_date;
      }
    }

    const result = await getQaLogsStats(params);

    if (result.code === 2000 && result.data) {
      statistics.value = result.data;

      // 更新统计卡片数据
      statisticsItems.value = [
        {
          label: "总查询",
          value: result.data.total_queries || 0,
          bgColor: "#1890ff",
          span: 6,
        },
        {
          label: "AI查询",
          value: result.data.ai_queries || 0,
          bgColor: "#722ed1",
          span: 6,
        },
        {
          label: "AI使用率",
          value: result.data.ai_usage_rate
            ? `${result.data.ai_usage_rate.toFixed(1)}%`
            : "0%",
          bgColor: "#52c41a",
          span: 6,
        },
        {
          label: "平均响应时间",
          value: result.data.avg_response_time_ms
            ? `${parseFloat(result.data.avg_response_time_ms).toFixed(0)}ms`
            : "0ms",
          bgColor: "#faad14",
          span: 6,
        },
      ];
    }
  } catch (error: any) {
    console.error("获取统计数据失败:", error);
  }
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchLogList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchLogList();
};

// 搜索
const handleSearch = (formData: Record<string, any>) => {
  Object.assign(filterForm, formData);
  pagination.currentPage = 1;
  fetchLogList();
  fetchStatistics();
};

// 重置筛选
const handleReset = () => {
  filterForm.date_range = "today";
  filterForm.start_date = "";
  filterForm.end_date = "";
  filterForm.log_type = "all";
  filterForm.used_ai = null;
  filterForm.min_response_time = null;
  filterForm.user_id = null;
  pagination.currentPage = 1;
  fetchLogList();
  fetchStatistics();
};

onMounted(() => {
  fetchLogList();
  fetchStatistics();
});
</script>

<template>
  <div class="log-page">
    <!-- 统计信息 -->
    <el-card v-if="statisticsItems.length > 0" style="margin-bottom: 20px">
      <DynamicStatistics :items="statisticsItems" :gutter="20" />
    </el-card>

    <el-card style="margin-bottom: 20px">
      <DynamicForm
        :form-config="formConfig"
        :model-value="filterForm"
        type="search"
        @search="handleSearch"
        @reset="handleReset"
      />
    </el-card>

    <el-card>
      <DynamicTable
        :columns="columns"
        :data="logList"
        :loading="loading"
        :pagination="pagination"
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.log-page {
  padding: 20px;
}
</style>
